package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @projectName: sky-take-out
 * @package: com.sky.aspect
 * @className: AutoFillAspect
 * @author: Eric
 * @description: TODO
 * @date: 2023/9/20 10:58
 * @version: 1.0
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    // 1.切点
    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    public void pt(){

    }

    // 2.通知方法
    @Before("pt()")
    public void autoFill(JoinPoint joinPoint){
        // 1.需要动态获取注释,并且获取注释中的属性(判断是增加还是更新)
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        try {
            // 2.动态获取入参,进行反射赋值
            Object arg = joinPoint.getArgs()[0];
            if (OperationType.INSERT == operationType){
                // 用反射获取对象的方法,然后进行动态赋值
                Method setCreatTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setCreatUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                setCreatTime.invoke(arg,LocalDateTime.now());
                setUpdateTime.invoke(arg,LocalDateTime.now());
                setCreatUser.invoke(arg, BaseContext.getCurrentId());
                setUpdateUser.invoke(arg,BaseContext.getCurrentId());
            }

            if (OperationType.UPDATE == operationType){
                Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                setUpdateTime.invoke(arg,LocalDateTime.now());
                setUpdateUser.invoke(arg,BaseContext.getCurrentId());
            }
        } catch (Exception e) {
            log.info("动态注入属性失败!");
        }


    }
}
